﻿using System.Windows;
using System.Windows.Input;
using RPGOnlineWPF.Model.MapEditor.Designers;
using RPGOnlineWPF.Renderer;
using SharpDX;
using SharpDX.Direct3D10;
using Device = SharpDX.Direct3D10.Device;

namespace RPGOnlineWPF.Model.MapEditor
{
	public class Map : SceneBase<D3D10>
	{
		private DepthStencilState m_depthStencilStateRef;

		public Map()
		{
			AddChild(new Grid(150, 150, new Color4(1, 1, 1, 0.2f)));
			var wall = new Wall();
			AddChild(wall);
			AddChild(new WallDesigner(wall));
		}

		public override void Attach()
		{
			base.Attach();

			var depthStencilStateDescription = new DepthStencilStateDescription();
			depthStencilStateDescription.DepthComparison = Comparison.Never;
			depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;
			depthStencilStateDescription.IsDepthEnabled = false;
			depthStencilStateDescription.IsStencilEnabled = false;

			m_depthStencilStateRef = new DepthStencilState(Renderer.Device, depthStencilStateDescription);
			Renderer.Device.OutputMerger.SetDepthStencilState(m_depthStencilStateRef, 1);
		}

		public override void Detach()
		{
			base.Detach();

			m_depthStencilStateRef.Dispose();
		}

		public override void RenderScene(DrawEventArgs args)
		{
			Device device = Renderer.Device;
			if (device == null)
				return;

			device.ClearRenderTargetView(Renderer.RenderTargetView, new Color4(0.1f, 0.1f, 0.1f, 1));

			m_children.ForEach(c => c.RenderScene(args));
		}

		public override void OnMouseDown(UIElement ui, MouseButtonEventArgs e)
		{
			foreach (var child in m_children)
			{
				child.OnMouseDown(ui, e);
				if (e.Handled)
					return;
			}

			base.OnMouseDown(ui, e);
		}

		public override void OnMouseMove(UIElement ui, MouseEventArgs e)
		{
			foreach (var child in m_children)
			{
				child.OnMouseMove(ui, e);
				if (e.Handled)
					return;
			}

			base.OnMouseMove(ui, e);
		}

		public override void OnMouseUp(UIElement ui, MouseButtonEventArgs e)
		{
			foreach (var child in m_children)
			{
				child.OnMouseUp(ui, e);
				if (e.Handled)
					return;
			}

			base.OnMouseUp(ui, e);
		}
	}
}